<template>
  <div class="login-page">
    <!-- Banner 图片 -->
    <div class="banner">
      <img
        src="@/assets/images/banner.jpg"
        alt="学校banner"
        class="banner-image"
      />
      <div class="banner-overlay"></div>
      <div class="banner-content">
        <div class="banner-title">
          <h1 class="platform-name">启迪智慧</h1>
          <p class="platform-desc">实验室管理系统</p>
        </div>
      </div>
    </div>

    <!-- 登录表单 -->
    <div class="login-container">
      <div class="login-box">
        <h2 class="title">用户登录</h2>

        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
        >
          <el-form-item prop="userCode">
            <el-input
              v-model="loginForm.userCode"
              placeholder="请输入账号"
              size="large"
              prefix-icon="User"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              size="large"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              size="large"
              class="login-btn"
              @click="handleLogin"
              :loading="loading"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>

        <div class="register-link">
          <span>还没有账号？</span>
          <router-link to="/register" class="link">立即注册</router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElForm } from "element-plus";
import { JSEncrypt } from "jsencrypt";
import { loginAPI, getPublicKeyAPI, LoginType } from "@/api/service/user";
import { setCookie } from "@/assets/js/cookie";

const router = useRouter();
const loginFormRef = ref<InstanceType<typeof ElForm>>();
const loading = ref(false);
const publicKey = ref("");

// 登录表单数据
const loginForm = reactive({
  userCode: "",
  password: "",
});

// 表单验证规则
const loginRules = {
  userCode: [{ required: true, message: "请输入账号", trigger: "blur" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度至少6位", trigger: "blur" },
  ],
};

// 获取公钥
const getPublicKey = async () => {
  try {
    const response = await getPublicKeyAPI();
    publicKey.value = response as any;
  } catch (error) {
    ElMessage.error("获取加密密钥失败");
  }
};

// 密码加密
const encryptPassword = (password: string) => {
  if (!publicKey.value) {
    ElMessage.error("加密密钥未获取");
    return "";
  }

  const encrypt = new JSEncrypt();
  encrypt.setPublicKey(publicKey.value);
  return encrypt.encrypt(password) || "";
};

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return;

  await loginFormRef.value.validate((valid: boolean) => {
    if (valid) {
      login();
    }
  });
};

const login = async () => {
  loading.value = true;

  try {
    // 加密密码
    const encryptedPassword = encryptPassword(loginForm.password);
    if (!encryptedPassword) {
      loading.value = false;
      return;
    }

    const loginData: LoginType = {
      userCode: loginForm.userCode,
      encryptedPassword,
    };

    const response = await loginAPI(loginData);
    const token = (response as any).token;
    const userInfo = (response as any).userInfo;
    ElMessage.success("登录成功");
    // 保存token到cookie（7天有效期）
    setCookie("token", token, 7);
    // 用户信息仍然保存到localStorage
    localStorage.setItem("userInfo", JSON.stringify(userInfo));
    // 跳转到主页
    router.push({
      name: "Portal",
    });
  } catch (error: any) {
    ElMessage.error(error.message);
  } finally {
    loading.value = false;
  }
};

// 页面初始化
onMounted(() => {
  getPublicKey();
});
</script>

<style scoped lang="scss">
.login-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.banner {
  position: relative;
  width: 100%;
  margin-bottom: 20px;
  overflow: hidden;

  .banner-image {
    width: 100%;
    height: auto;
    display: block;
  }

  .banner-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(
      135deg,
      rgb(102, 126, 234, 0.8) 0%,
      rgb(118, 75, 162, 0.8) 100%
    );
  }

  .banner-content {
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    z-index: 2;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
  }

  .banner-title {
    .platform-name {
      font-size: 3.6rem;
      font-weight: 700;
      color: white;
      margin: 0 0 8px 0;
      text-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
      letter-spacing: 2px;
    }

    .platform-desc {
      font-size: 3rem;
      color: rgba(255, 255, 255, 0.9);
      margin: 0;
      font-weight: 400;
      text-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);
      letter-spacing: 1px;
    }
  }
}

.login-container {
  position: absolute;
  bottom: 2rem;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  z-index: 999;
}

.login-box {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  min-width: 400px;
  max-width: 500px;
  width: 100%;

  .title {
    text-align: center;
    font-size: 28px;
    font-weight: 600;
    color: #333;
    margin-bottom: 30px;
  }

  .login-form {
    .el-form-item {
      margin-bottom: 20px;
    }

    .el-input {
      --el-input-height: 48px;
    }

    .login-btn {
      width: 100%;
      height: 48px;
      font-size: 16px;
      font-weight: 600;
      margin-top: 10px;
    }
  }

  .register-link {
    text-align: center;
    margin-top: 20px;
    color: #666;

    .link {
      color: #409eff;
      text-decoration: none;
      margin-left: 5px;

      &:hover {
        text-decoration: underline;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .banner {
    margin-bottom: 15px;

    .banner-title {
      .platform-name {
        font-size: 24px;
        margin-bottom: 4px;
        letter-spacing: 1px;
      }

      .platform-desc {
        font-size: 14px;
      }
    }
  }

  .login-container {
    padding: 20px 15px;
  }

  .login-box {
    min-width: auto;
    padding: 30px 25px;
  }
}
</style>
